package cn.websocket.controller;

import cn.websocket.utils.RedisUtils;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;

import jakarta.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

import static cn.websocket.constant.StatusConstant.*;

/**
 * <h3>WebSocket</h3>
 * <p>
 *     二维码生成接口
 * </p>
 *
 * @author gdw
 * @since 2025-08-20 09:42:53
 */
@RestController
@RequiredArgsConstructor
@Slf4j
public class CommonController {
    private final DefaultKaptcha captchaProducer;
    private final RedisUtils redisUtils;
    @GetMapping("/captcha")
    public void getCaptcha(HttpServletResponse response, HttpServletRequest request) {
        try {
            // 设置响应头防止缓存
            response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/png");

            // 生成验证码
            String capText = captchaProducer.createText();

            // 使用IP+时间戳作为Key，更稳定
            String clientIp = request.getRemoteAddr();
            long minuteTimestamp = System.currentTimeMillis() / 120000;
            String redisKey = CODE_REGISTER + clientIp + ":" + minuteTimestamp;

            // 存储到Redis，2分钟过期
            redisUtils.set(redisKey, capText, 120);

            // 生成并输出图片
            BufferedImage bi = captchaProducer.createImage(capText);
            try (ServletOutputStream out = response.getOutputStream()) {
                ImageIO.write(bi, "png", out);
                out.flush();
            }

        } catch (IOException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            log.error("验证码生成失败", e);
        }
    }
}
